package com.sav.common.controller;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.sav.common.dao.CategoryDAO;
import com.sav.common.dao.ProductDAO;
import com.sav.common.forms.ProductForm;
import com.sav.common.validators.ProductValidator;


@Controller

public class FileUploadController {
	
	@Autowired(required = true)
    private CategoryDAO categoryDAO;
	
	@Autowired(required = true)
    private ProductDAO productDAO;
	
	
	@RequestMapping(value="/addProduct", method = RequestMethod.POST)
	public String processFormAdd(
			@RequestParam("file") MultipartFile file,
			ProductForm productForm, 
			BindingResult result) {

		if (isValid(productForm, result)) {
			int idProduct = productDAO.addProduct(productForm);
			moveFile(file, idProduct);
		}
		return "addProduct";
	}
	
	@RequestMapping(value="/editProduct", method = RequestMethod.POST)
	public String processFormEdit(
			@RequestParam("file") MultipartFile file,
			ProductForm productForm, 
			BindingResult result) {
		if (isValid(productForm, result)) {
			productDAO.changeProduct(productForm);
			moveFile(file, Integer.valueOf(productForm.getIdProduct()));
		}
		return "editProduct";
	}
	
	public boolean isValid(ProductForm productForm, BindingResult result) {
		ProductValidator productValidator = new ProductValidator();
		productValidator.validate(productForm, result);
		return !result.hasErrors();
	}
	
	public void moveFile(MultipartFile file, int id) {
		if (!file.getOriginalFilename().equals("")) {
			File dest = new File(Consts.filePlaceToUpload + id + ".jpg");
			if (dest.exists()) dest.delete();
			try {
				file.transferTo(dest);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
					e.printStackTrace();
			}
		}
	}
		
}
